#pragma once
#include <unordered_map>
#include <mutex>
#include "util.hpp"
/*
    在线用户管理模块
    实现判断用户是否在线
    获取在线用户的网络连接
*/

class online_manager
{
public:
    void enter_game_hall(uint64_t id, wsserver_t::connection_ptr conn)
    {
        std::unique_lock<std::mutex>(_mutex);
        _hall_user.insert({id, conn});
    }

    void enter_game_room(uint64_t id, wsserver_t::connection_ptr conn)
    {
        std::unique_lock<std::mutex>(_mutex);
        _room_user.insert({id, conn});
    }

    void exit_game_hall(uint64_t id)
    {
        std::unique_lock<std::mutex>(_mutex);
        _hall_user.erase(id);
    }

    void exit_game_room(uint64_t id)
    {
        std::unique_lock<std::mutex>(_mutex);
        _room_user.erase(id);
    }

    bool is_in_game_hall(uint64_t id)
    {
        std::unique_lock<std::mutex>(_mutex);
        auto pos = _hall_user.find(id);
        return pos != _hall_user.end();
    }

    bool is_in_game_room(uint64_t id)
    {
        std::unique_lock<std::mutex>(_mutex);
        auto pos = _room_user.find(id);
        return pos != _room_user.end();
    }
    void print()
    {
        for(auto a:_room_user){
            LOG(INFO,"_room_user:%d\n",a.first);
        }
    }
    wsserver_t::connection_ptr get_conn_from_hall(uint64_t id)
    {
        std::unique_lock<std::mutex>(_mutex);
        if (is_in_game_hall(id))
            return _hall_user[id];
        return wsserver_t::connection_ptr();
    }

    wsserver_t::connection_ptr get_conn_from_room(uint64_t id)
    {
        std::unique_lock<std::mutex>(_mutex);
        if (is_in_game_room(id))
            return _room_user[id];
        return wsserver_t::connection_ptr();
    }

private:
    std::mutex _mutex;
    // 大厅用户管理 id <-> connection
    std::unordered_map<uint64_t, wsserver_t::connection_ptr> _hall_user;
    // 房间用户管理 id <-> connection
    std::unordered_map<uint64_t, wsserver_t::connection_ptr> _room_user;
};